<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\extra\wx\WxSdk;
use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;

/**
 * 场馆管理
 *
 * @icon fa fa-circle-o
 */
class Gymnasium extends Backend
{

    /**
     * Gymnasium模型对象
     * @var \app\admin\model\Gymnasium
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Gymnasium;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isJoinList", $this->model->getIsJoinList());
        $this->view->assign("isActivityList", $this->model->getIsActivityList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if (!$this->auth->isSuperAdmin() && Session::get('admin.id') !== 2) {
            $ids = Session::get('admin.gymnasium_id');
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (Session::get('admin.id') > 2) {
                unset($params['user_id']);
                unset($params['type']);
                unset($params['license_image']);
                unset($params['card_up_image']);
                unset($params['percentage']);
                unset($params['status']);
            }
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    // 更新教练定位信息
                    Db::name('coach')->where(['gymnasium_id' => $ids])->update(['longitude' => $params['longitude'], 'latitude' => $params['latitude']]);

                    /*
                     * 同步信息到admin表 gymnasium_finance(余额表) 否则场馆无法登录后台，无法获得余额
                     * 场馆通过审核后，小程序端下发通知，引导用户自行登录后台更新信息
                     */
                    $find = Db::name('admin')->where(['gymnasium_id' => $ids])->find();
                    if ($this->auth->isSuperAdmin() || Session::get('admin.id') == 2) {
                        if ($params['status'] == 1) {
                            $salt = Random::alnum();
                            if (!$find) {
                                $admin_id = Db::name('admin')->insertGetId([
                                    'username'     => $params['phone'],
                                    'gymnasium_id' => $ids,
                                    'nickname'     => $params['name'],
                                    'salt'         => $salt,
                                    'password'     => md5(md5(123456) . $salt),
                                    'email'        => 'admin-' . $salt . '@website.com',
                                    'avatar'       => '/assets/img/avatar.png',
                                    'createtime'   => time(),
                                    'updatetime'   => time(),
                                ]);
                                Db::name('auth_group_access')->insert(['uid' => $admin_id, 'group_id' => 6]);
                                Db::name('gymnasium_finance')->insert(['gymnasium_id' => $ids]);
                                // 场馆审核通过，下发通知
                                $pay = get_addon_config('epay');
                                $app_id = $pay['wechat']['app_id'];
                                $app_secret = $pay['wechat']['app_secret'];
                                $data = [
                                    'thing18' => ['value' => $params['name']],
                                    'thing4'  => ['value' => '请第一时间修改密码，防止造成您的损失'],
                                    'phrase5' => ['value' => '审核通过'],
                                    'thing11' => ['value' => '点击查看详情'],
                                ];
                                // 查找user表的 open_id  字段
                                $find_open = Db::name('user')
                                    ->alias('user')
                                    ->where(['gymnasium.id' => $ids])
                                    ->join('gymnasium gymnasium', 'user.id = gymnasium.user_id', 'LEFT')
                                    ->field('user.open_id')
                                    ->find();
                                $result = (new WxSdk($app_id, $app_secret))->subscribeSend($find_open['open_id'], 'kvmaVk0OuBOwrZKjTiMJ1je4JK6OeBzrtShS9lqakjU', 'pages/content/index?id=4', $data);
                            } else {
                                Db::name('admin')->where(['username' => $params['phone']])->update(['status' => 'normal']);
                            }
                        } else {
                            if ($find) Db::name('admin')->where(['username' => $params['phone']])->update(['status' => 'hidden', 'token' => '']);
                        }
                    }

                    // 场馆是否参加活动
                    if (!empty($params['is_join'])) {
                        Db::name('admin')->where(['gymnasium_id' => $ids])->update(['is_join' => $params['is_join']]);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
